package cc.mrbird.febs.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author MrBird
 */
public class MD5Util {

    protected MD5Util() {

    }

    private static final String ALGORITH_NAME = "md5";

    private static final int HASH_ITERATIONS = 5;

    public static String encrypt(String username, String password) {
        String source = StringUtils.lowerCase(username);
        password = StringUtils.lowerCase(password);
        return new SimpleHash(ALGORITH_NAME, password, ByteSource.Util.bytes(source), HASH_ITERATIONS).toHex();
    }


    /**
     * 使用md5的算法进行加密
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        int mixNum = 32 - md5code.length();
        for (int i = 0; i < mixNum; i++) {
            md5code = "0" + md5code;
        }
        return md5code.toUpperCase();
    }


    /**
     * md5(md5(时间戳+随机字符串+秘钥)+data)
     *
     * @param params
     * @param sign
     * @param timeStampStr
     * @param uuid
     * @return
     */
    public static boolean verify(String sign, String params, String timeStampStr, String uuid, String key) {
        if (sign.equals(md5(md5((timeStampStr + uuid + key)) + params))) {
            return true;
        }
        return false;
    }
}
